package com.epichust.bootumpp.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.epichust.bootumpp.model.dao.SerialCodeDao;
import com.epichust.bootumpp.model.entity.SerialCode;
import com.epichust.bootumpp.service.ISerialCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ：longyang
 * @date ：Created in 2020/12/18 14:11
 * @description：序列码接口实现类
 */
@Service
@Transactional
public class SerialCodeServiceImpl implements ISerialCodeService {

    @Autowired
    private SerialCodeDao serialCodeDao;
    /**
     * 生成序列码
     *
     * @param map
     * @return
     */
    @Override
    public String generateSerialCode(Map<String, String> map) throws Exception {
        String userId = map.get("userId") == null ? "SYSTEM" : map.get("userId");
        String head = map.get("head");//头部码
        String middle = map.get("middle") == null ? "" : map.get("middle");//中间码
        String siteCode = map.get("siteCode");//工厂编码
        String workCenterCode = map.get("workCenterCode");//工作中心编码
        String waterFlag = map.get("waterFlag");//是否生成流水码（0是，1否）

        //当中间码参数为date时，则中间码根据相应格式，获取当前时间编码
        if(middle.indexOf("date") != -1){
            String [] arr = middle.split("-");
            String format = "";
            if(arr.length < 2){
                format = "yyyyMMdd";
            }else{
                format = arr[1];
            }
            Date date = new Date();
            SimpleDateFormat sif = new SimpleDateFormat(format);
            String result = sif.format(date);
            middle = result;
        }
        SerialCode search = new SerialCode();
        search.setHead(head);
        search.setMiddle(middle);
        //生成流水码
        String waterCode = "";
        if("0".equals(waterFlag)){
            if(map.get("waterNumber") == null){
                throw new Exception("当确认生成流水码时，传入的流水码位数（waterNumber）不能为空");
            }
            Integer waterNumber = Integer.parseInt(map.get("waterNumber"));//生成流水码位数
            List<SerialCode> slist = serialCodeDao.getSerialCodeByParams(search);
            //当存在相同编码的流水码时，则在原基础上累加
            if(!slist.isEmpty() && !StringUtils.isEmpty(slist.get(0).getWaterCode())){
                String lastWaterCode = slist.get(0).getWaterCode();
                int flag = Integer.valueOf(lastWaterCode) + 1;
                StringBuffer buffer = new StringBuffer();
                String flagCode = String.valueOf(flag);
                for(int j=0;j<waterNumber-flagCode.length();j++){
                    buffer.append("0");
                }
                if(flagCode.length()<=waterNumber){
                    flagCode = buffer.toString()+flagCode;
                }else{
                    throw new Exception("生成序列码位数大于输入的位数，无法生成！");
                }
                waterCode = flagCode;
            }else{//当相同编码没有生成流水码的时候，从00001开始
                String zero = "";
                for(int i=0;i<waterNumber;i++){
                    zero +="0";
                }
                waterCode = zero;
            }

        }
        String connectFlag = map.get("connectFlag") == null ? "" : map.get("connectFlag");//连接符
        //拼接序列码（例：PN-TO-000001）
        String code = head + connectFlag + middle + connectFlag + waterCode;
        List<SerialCode> sslist = serialCodeDao.getSerialCodeByCode(code);
        if(!sslist.isEmpty()){
            throw new Exception("系统繁忙，请再重试");
        }
        SerialCode serialCode = new SerialCode();
        serialCode.setCode(code);
        serialCode.setConnectFlag(connectFlag);
        serialCode.setHead(head);
        serialCode.setMiddle(middle);
        serialCode.setWaterCode(waterCode);
        serialCode.setCreateId(userId);
        serialCode.setCreateDate(new Date());
        serialCode.setModifyId(userId);
        serialCode.setModifyDate(new Date());
        serialCode.setSiteCode(siteCode);
        serialCode.setWorkCenterCode(workCenterCode);
        //先将序列码信息写入表中
        serialCodeDao.insertSerialCode(serialCode);

        //返回序列码
        return code;
    }

    /**
     * 分页查询序列码
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public List<SerialCode> getAllSerialCode(Map<String, String> map) throws Exception {
        List<SerialCode> list = serialCodeDao.getAllSerialCode(map);
        return list;
    }
}
